/**
 * 商品管理相关JavaScript
 */
document.addEventListener('DOMContentLoaded', function() {
    if (typeof jQuery === 'undefined') {
        console.error('jQuery is not loaded! Product functionality will not work.');
        return;
    }
    
    // 使用jQuery
    jQuery(function($) {
        // 获取上下文路径
        var contextPath = $('meta[name="context-path"]').attr('content') || '';
        let currentPage = 1;
        let pageSize = 10;
        let totalPages = 0;
        let isEdit = false;
        
        // 加载商品列表
        function loadProducts(page = 1) {
            currentPage = page;
            
            let url = contextPath + "/admin/products/list?pageNum=" + page + "&pageSize=" + pageSize;
            
            // 添加过滤条件
            const name = $('#searchName').val();
            const category = $('#searchCategory').val();
            const status = $('#searchStatus').val();
            
            if (name) url += "&name=" + encodeURIComponent(name);
            if (category) url += "&categoryId=" + category;
            if (status !== "") url += "&status=" + status;
            
            $.get(url, function(res) {
                console.log("API响应:", res); // 调试信息
                if (res.code === 200 || res.success === true) {
                    renderProducts(res.data.records || []);
                    renderPagination(res.data.current, res.data.pages);
                    totalPages = res.data.pages;
                } else {
                    alert("加载商品失败: " + (res.message || res.msg));
                }
            }).fail(function(jqXHR, textStatus, errorThrown) {
                console.error("API请求失败:", textStatus, errorThrown);
                alert("加载数据失败，请检查网络连接或联系管理员");
            });
        }
        
        // 渲染商品列表
        function renderProducts(products) {
            const $tbody = $('#productTableBody');
            $tbody.empty();
            
            if (products.length === 0) {
                $tbody.html('<tr><td colspan="8" class="text-center">没有找到商品数据</td></tr>');
                return;
            }
            
            products.forEach(function(product) {
                const statusBadge = product.status === 1 
                    ? '<span class="badge badge-success">上架</span>' 
                    : '<span class="badge badge-secondary">下架</span>';
                
                const imgSrc = product.mainImage ? contextPath + product.mainImage : contextPath + "/static/images/product-default.jpg";
                
                let tr = '<tr>' +
                    '<td>' + product.id + '</td>' +
                    '<td><div class="product-image-wrapper"><img src="' + imgSrc + '" alt="' + product.name + '"></div></td>' +
                    '<td>' + product.name + '</td>' +
                    '<td>￥' + product.price + '</td>' +
                    '<td>' + product.stock + '</td>' +
                    '<td>' + getCategoryName(product.categoryId) + '</td>' +
                    '<td>' + statusBadge + '</td>' +
                    '<td class="table-actions">' +
                        '<button class="btn btn-sm btn-outline-primary edit-btn" data-id="' + product.id + '">' +
                            '<i class="fas fa-edit"></i> 编辑' +
                        '</button> ' +
                        '<button class="btn btn-sm btn-outline-danger delete-btn" data-id="' + product.id + '">' +
                            '<i class="fas fa-trash"></i> 删除' +
                        '</button> ' +
                        '<button class="btn btn-sm btn-outline-' + (product.status === 1 ? 'warning' : 'success') + ' status-btn" ' +
                            'data-id="' + product.id + '" ' +
                            'data-status="' + (product.status === 1 ? '0' : '1') + '">' +
                            (product.status === 1 ? '下架' : '上架') +
                        '</button>' +
                    '</td>' +
                '</tr>';
                $tbody.append(tr);
            });
            
            // 绑定编辑按钮事件
            $('.edit-btn').click(function() {
                const productId = $(this).data('id');
                editProduct(productId);
            });
            
            // 绑定删除按钮事件
            $('.delete-btn').click(function() {
                const productId = $(this).data('id');
                if (confirm('确定要删除这个商品吗？')) {
                    deleteProduct(productId);
                }
            });
            
            // 绑定状态切换按钮事件
            $('.status-btn').click(function() {
                const productId = $(this).data('id');
                const status = $(this).data('status');
                const statusText = status === 1 ? '上架' : '下架';
                
                if (confirm('确定要将该商品' + statusText + '吗？')) {
                    updateProductStatus(productId, status);
                }
            });
        }
        
        // 渲染分页
        function renderPagination(current, total) {
            const $pagination = $('#pagination');
            $pagination.empty();
            
            if (total <= 1) return;
            
            let startPage = Math.max(1, current - 2);
            let endPage = Math.min(total, current + 2);
            
            // 上一页
            let prevDisabled = current == 1 ? 'disabled' : '';
            $pagination.append(
                '<li class="page-item ' + prevDisabled + '">' +
                '<a class="page-link" href="javascript:;" data-page="' + (current - 1) + '">上一页</a>' +
                '</li>'
            );
            
            // 页码
            for (let i = startPage; i <= endPage; i++) {
                let active = i == current ? 'active' : '';
                $pagination.append(
                    '<li class="page-item ' + active + '">' +
                    '<a class="page-link" href="javascript:;" data-page="' + i + '">' + i + '</a>' +
                    '</li>'
                );
            }
            
            // 下一页
            let nextDisabled = current == total ? 'disabled' : '';
            $pagination.append(
                '<li class="page-item ' + nextDisabled + '">' +
                '<a class="page-link" href="javascript:;" data-page="' + (current + 1) + '">下一页</a>' +
                '</li>'
            );
            
            // 绑定分页点击事件
            $('.page-link').click(function() {
                if (!$(this).parent().hasClass('disabled')) {
                    const page = $(this).data('page');
                    loadProducts(page);
                }
            });
        }
        
        // 获取分类名称
        function getCategoryName(categoryId) {
            const category = findCategoryById(categoryId);
            return category ? category.name : '未知分类';
        }
        
        // 根据ID查找分类对象
        function findCategoryById(categoryId) {
            // 从页面中获取分类数据
            if (typeof window.categories === 'undefined') {
                // 初始化分类数据，从select选项中获取
                window.categories = [];
                $('#productCategory option').each(function() {
                    const value = $(this).val();
                    if (value) {
                        window.categories.push({
                            id: parseInt(value),
                            name: $(this).text()
                        });
                    }
                });
            }
            
            return window.categories.find(function(c) { 
                return c.id === (typeof categoryId === 'string' ? parseInt(categoryId) : categoryId); 
            });
        }
        
        // 编辑商品
        function editProduct(productId) {
            isEdit = true;
            $('#productModalTitle').text('编辑商品');
            
            // 获取商品详情
            $.get(contextPath + "/admin/products/list", function(res) {
                if (res.code === 200 || res.success === true) {
                    const products = res.data.records || [];
                    const product = products.find(function(p) { return p.id === productId; });
                    if (product) {
                        // 填充表单
                        $('#productId').val(product.id);
                        $('#productName').val(product.name);
                        $('#productCategory').val(product.categoryId);
                        $('#productPrice').val(product.price);
                        $('#productStock').val(product.stock);
                        $('#productSubtitle').val(product.subtitle);
                        $('#productImage').val(product.mainImage);
                        $('#productDetail').val(product.detail);
                        $('#productIsHot').prop('checked', product.isHot === 1);
                        $('#productIsNew').prop('checked', product.isNew === 1);
                        $('#productStatus').prop('checked', product.status === 1);
                        
                        // 显示图片预览
                        if (product.mainImage) {
                            $('#imagePreview').attr('src', contextPath + product.mainImage);
                            $('#previewContainer').show();
                        } else {
                            $('#previewContainer').hide();
                        }
                        
                        // 打开模态框
                        $('#productModal').modal('show');
                    } else {
                        alert('找不到该商品');
                    }
                } else {
                    alert("获取商品失败: " + (res.message || res.msg));
                }
            });
        }
        
        // 删除商品
        function deleteProduct(productId) {
            $.ajax({
                url: contextPath + "/admin/products/delete/" + productId,
                type: "POST",
                success: function(res) {
                    if (res.code === 200 || res.success === true) {
                        alert("删除成功");
                        loadProducts(currentPage);
                    } else {
                        alert("删除失败: " + (res.message || res.msg));
                    }
                },
                error: function() {
                    alert("删除失败，服务器错误");
                }
            });
        }
        
        // 更新商品状态
        function updateProductStatus(productId, status) {
            $.ajax({
                url: contextPath + "/admin/products/status/" + productId + "/" + status,
                type: "POST",
                success: function(res) {
                    if (res.code === 200 || res.success === true) {
                        alert("商品状态已更新");
                        loadProducts(currentPage);
                    } else {
                        alert("更新状态失败: " + (res.message || res.msg));
                    }
                },
                error: function() {
                    alert("更新状态失败，服务器错误");
                }
            });
        }
        
        // 保存商品
        function saveProduct() {
            const product = {
                name: $('#productName').val(),
                categoryId: parseInt($('#productCategory').val()),
                price: parseFloat($('#productPrice').val()),
                stock: parseInt($('#productStock').val()),
                subtitle: $('#productSubtitle').val(),
                mainImage: $('#productImage').val(),
                detail: $('#productDetail').val(),
                isHot: $('#productIsHot').is(':checked') ? 1 : 0,
                isNew: $('#productIsNew').is(':checked') ? 1 : 0,
                status: $('#productStatus').is(':checked') ? 1 : 0
            };
            
            if (isEdit) {
                product.id = parseInt($('#productId').val());
            }
            
            $.ajax({
                url: contextPath + "/admin/products/" + (isEdit ? "update" : "add"),
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify(product),
                success: function(res) {
                    if (res.code === 200 || res.success === true) {
                        alert(isEdit ? "更新成功" : "添加成功");
                        $('#productModal').modal('hide');
                        loadProducts(currentPage);
                    } else {
                        alert((isEdit ? "更新失败: " : "添加失败: ") + (res.message || res.msg));
                    }
                },
                error: function() {
                    alert(isEdit ? "更新失败，服务器错误" : "添加失败，服务器错误");
                }
            });
        }
        
        // 图片上传
        function uploadImage() {
            const formData = new FormData();
            const fileInput = document.getElementById('fileInput');
            
            if (fileInput.files.length === 0) {
                alert('请选择图片');
                return;
            }
            
            formData.append('file', fileInput.files[0]);
            
            // 显示上传进度
            $('#uploadProgress').removeClass('d-none');
            
            $.ajax({
                url: contextPath + "/admin/upload",
                type: "POST",
                data: formData,
                processData: false,
                contentType: false,
                success: function(res) {
                    $('#uploadProgress').addClass('d-none');
                    
                    if (res.code === 200 || res.success === true) {
                        $('#productImage').val(res.data);
                        $('#imagePreview').attr('src', contextPath + res.data);
                        $('#previewContainer').show();
                        $('#uploadModal').modal('hide');
                    } else {
                        alert("上传失败: " + (res.message || res.msg));
                    }
                },
                error: function() {
                    $('#uploadProgress').addClass('d-none');
                    alert("上传失败，服务器错误");
                }
            });
        }
        
        // 图片预览
        $('#fileInput').change(function() {
            if (this.files && this.files[0]) {
                var reader = new FileReader();
                reader.onload = function(e) {
                    $('#uploadPreview').attr('src', e.target.result);
                    $('#uploadPreviewContainer').removeClass('d-none');
                }
                reader.readAsDataURL(this.files[0]);
            }
        });
        
        // 事件绑定
        
        // 搜索按钮点击
        $('#searchBtn').click(function() {
            loadProducts(1);
        });
        
        // 添加商品按钮点击
        $('#productModal').on('show.bs.modal', function(e) {
            if (!isEdit) {
                $('#productModalTitle').text('添加商品');
                $('#productForm').trigger('reset');
                $('#productId').val('');
                $('#previewContainer').hide();
            }
        });
        
        // 图片上传按钮点击
        $('#uploadImageBtn').click(function() {
            $('#uploadForm').trigger('reset');
            $('#uploadPreviewContainer').addClass('d-none');
            $('#uploadModal').modal('show');
        });
        
        // 确认上传按钮点击
        $('#confirmUploadBtn').click(function() {
            uploadImage();
        });
        
        // 保存商品按钮点击
        $('#saveProductBtn').click(function() {
            // 表单验证
            if (!$('#productName').val()) {
                alert('请输入商品名称');
                return;
            }
            if (!$('#productCategory').val()) {
                alert('请选择商品分类');
                return;
            }
            if (!$('#productPrice').val() || parseFloat($('#productPrice').val()) <= 0) {
                alert('请输入有效的商品价格');
                return;
            }
            if (!$('#productStock').val() || parseInt($('#productStock').val()) < 0) {
                alert('请输入有效的库存数量');
                return;
            }
            
            saveProduct();
        });
        
        // 初始加载
        loadProducts();
    });
}); 